import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ManagerDAOImpl implements ManagerDAO {
    @Override
    public Manager findByAccount(String account) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "SELECT * FROM Manager WHERE Account =?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, account);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                Manager manager = new Manager();
                manager.setMname(resultSet.getString("MName"));
                manager.setMnumber(resultSet.getString("Mnumber"));
                return manager;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Manager> getAllManagers() {
        List<Manager> managers = new ArrayList<>();
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "SELECT * FROM Manager";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Manager manager = new Manager();
                manager.setMname(resultSet.getString("MName"));
                manager.setMnumber(resultSet.getString("Mnumber"));
                managers.add(manager);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return managers;
    }

    @Override
    public void save(Manager manager) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "INSERT INTO Manager (Account, MName, Mnumber) VALUES (?,?,?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, manager.getAccount());
            preparedStatement.setString(2, manager.getMname());
            preparedStatement.setString(3, manager.getMnumber());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}